<template>
  <div>
    <!--顶部logo-->
    <div box-border px-40 h-24 flex items-end>
      <img :src="logoImg" :style="{ height: '80px' }" @click="router.push('/')" />
      <div ml-6 font-medium text-2xl mb-7>欢迎登录</div>
    </div>
    <!--登录主体-->
    <div class="login-container">
      <!--<img class="demo-carousel" src="https://lili-system.oss-cn-beijing.aliyuncs.com/background.jpg" alt="">-->
      <div class="form-box">
        <div class="login-title">
          <span :class="data.loginType === 'accountLogin' ? 'current' : ''" @click="toggleLoginType('accountLogin')">
            账号登录
          </span>
          <span class="line"></span>
          <span :class="data.loginType === 'authCodeLogin' ? 'current' : ''" @click="toggleLoginType('authCodeLogin')">
            验证码登录
          </span>
          <!--<span class="scanner-code" @click="data.scannerCodeLoginFLag = !data.scannerCodeLoginFLag">{{data.scannerCodeLoginFLag?'返回':'扫码登录'}}</span>-->
        </div>
        <!--账号密码登录-->
        <a-form
          ref="accountLoginRef"
          size="large"
          layout="vertical"
          :style="{ width: '310px' }"
          @submit-success="handleSubmit"
          :model="data.accountLoginForm"
          v-if="data.loginType === 'accountLogin' && !data.scannerCodeLoginFLag">
          <a-form-item :hide-asterisk="true" field="username" :rules="[REQUIRED, VARCHAR20]">
            <a-input v-model="data.accountLoginForm.username" size="large" allow-clear placeholder="请输入用户名">
              <template #prefix>
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 1024 1024">
                  <path
                    fill="currentColor"
                    d="M628.736 528.896A416 416 0 0 1 928 928H96a415.872 415.872 0 0 1 299.264-399.104L512 704zM720 304a208 208 0 1 1-416 0a208 208 0 0 1 416 0" />
                </svg>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item :hide-asterisk="true" field="password" :rules="[REQUIRED, VARCHAR20]">
            <a-input-password
              v-model="data.accountLoginForm.password"
              value="large"
              allow-clear
              placeholder="请输入密码">
              <template #prefix>
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                  <path
                    fill="currentColor"
                    d="M19 10h1a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V11a1 1 0 0 1 1-1h1V9a7 7 0 0 1 14 0zm-2 0V9A5 5 0 0 0 7 9v1zm-6 4v4h2v-4z" />
                </svg>
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item no-style>
            <a-button
              html-type="submit"
              type="primary"
              status="danger"
              long
              :style="{ width: '310px' }"
              :loading="loading">
              登录
            </a-button>
          </a-form-item>
        </a-form>
        <!--验证码登录-->
        <a-form
          ref="authCodeLoginRef"
          size="large"
          layout="vertical"
          :style="{ width: '310px' }"
          @submit-success="handleSubmitAuthCode"
          :model="data.authCodeLoginForm"
          v-if="data.loginType === 'authCodeLogin' && !data.scannerCodeLoginFLag">
          <a-form-item :hide-asterisk="true" field="mobile" :rules="[REQUIRED]">
            <a-input v-model="data.authCodeLoginForm.mobile" allow-clear placeholder="请输入手机号">
              <template #prefix>
                <icon-lock />
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 256 256">
                  <path
                    fill="currentColor"
                    d="M231.88 175.08A56.26 56.26 0 0 1 176 224C96.6 224 32 159.4 32 80a56.26 56.26 0 0 1 48.92-55.88a16 16 0 0 1 16.62 9.52l21.12 47.15v.12A16 16 0 0 1 117.39 96c-.18.27-.37.52-.57.77L96 121.45c7.49 15.22 23.41 31 38.83 38.51l24.34-20.71a8.12 8.12 0 0 1 .75-.56a16 16 0 0 1 15.17-1.4l.13.06l47.11 21.11a16 16 0 0 1 9.55 16.62" />
                </svg>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item :hide-asterisk="true" field="code" :rules="[REQUIRED]">
            <a-input v-model="data.authCodeLoginForm.code" allow-clear placeholder="请输入手机验证码">
              <template #prefix>
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                  <g fill="none">
                    <path
                      fill-rule="evenodd"
                      clip-rule="evenodd"
                      d="M2 5a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3h-3.586l-3.707 3.707A1 1 0 0 1 6 17v-3H5a3 3 0 0 1-3-3V5zm20 4v6c0 1-.6 3-3 3h-1v3c0 .333-.2 1-1 1c-.203 0-.368-.043-.5-.113L12.613 18H9l3-3h3c1.333 0 4-.8 4-4V6c1 0 3 .6 3 3z"
                      fill="currentColor" />
                  </g>
                </svg>
              </template>
              <template #append>
                <span class="code-msg" @click="sendCode">{{ data.codeMsg }}</span>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item no-style>
            <a-button
              @click.stop="verifyBtnClick"
              :status="data.verifyStatus ? 'success' : 'danger'"
              long
              :style="{ marginBottom: '20px' }"
              :loading="loading">
              {{ data.verifyStatus ? '验证通过' : '点击完成安全验证' }}
            </a-button>
          </a-form-item>
          <a-form-item no-style>
            <a-button
              html-type="submit"
              type="primary"
              status="danger"
              long
              :style="{ width: '310px' }"
              :loading="loading">
              登录
            </a-button>
          </a-form-item>
        </a-form>
        <!--扫码登录-->
        <div v-if="data.scannerCodeLoginFLag">扫码登录111</div>

        <!--其他登录方式/注册-->
        <div class="other">
          <div>
            <span>
              <svg
                t="1631154795933"
                class="icon"
                @click="handleWebLogin('QQ')"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="4969"
                width="24"
                height="24">
                <path
                  d="M824.8 613.2c-16-51.4-34.4-94.6-62.7-165.3C766.5 262.2 689.3 112 511.5 112 331.7 112 256.2 265.2 261 447.9c-28.4 70.8-46.7 113.7-62.7 165.3-34 109.5-23 154.8-14.6 155.8 18 2.2 70.1-82.4 70.1-82.4 0 49 25.2 112.9 79.8 159-26.4 8.1-85.7 29.9-71.6 53.8 11.4 19.3 196.2 12.3 249.5 6.3 53.3 6 238.1 13 249.5-6.3 14.1-23.8-45.3-45.7-71.6-53.8 54.6-46.2 79.8-110.1 79.8-159 0 0 52.1 84.6 70.1 82.4 8.5-1.1 19.5-46.4-14.5-155.8z"
                  p-id="4970"
                  fill="#1296db"></path>
              </svg>
            </span>
            <span>
              <svg
                t="1631154766336"
                class="icon"
                @click="handleWebLogin('WECHAT_PC')"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="3844"
                width="24"
                height="24">
                <path
                  d="M683.058 364.695c11 0 22 1.016 32.943 1.976C686.564 230.064 538.896 128 370.681 128c-188.104 0.66-342.237 127.793-342.237 289.226 0 93.068 51.379 169.827 136.725 229.256L130.72 748.43l119.796-59.368c42.918 8.395 77.37 16.79 119.742 16.79 11 0 21.46-0.48 31.914-1.442a259.168 259.168 0 0 1-10.455-71.358c0.485-148.002 128.744-268.297 291.403-268.297l-0.06-0.06z m-184.113-91.992c25.99 0 42.913 16.79 42.913 42.575 0 25.188-16.923 42.579-42.913 42.579-25.45 0-51.38-16.85-51.38-42.58 0-25.784 25.93-42.574 51.38-42.574z m-239.544 85.154c-25.384 0-51.374-16.85-51.374-42.58 0-25.784 25.99-42.574 51.374-42.574 25.45 0 42.918 16.79 42.918 42.575 0 25.188-16.924 42.579-42.918 42.579z m736.155 271.655c0-135.647-136.725-246.527-290.983-246.527-162.655 0-290.918 110.88-290.918 246.527 0 136.128 128.263 246.587 290.918 246.587 33.972 0 68.423-8.395 102.818-16.85l93.809 50.973-25.93-84.677c68.907-51.93 120.286-119.815 120.286-196.033z m-385.275-42.58c-16.923 0-34.452-16.79-34.452-34.179 0-16.79 17.529-34.18 34.452-34.18 25.99 0 42.918 16.85 42.918 34.18 0 17.39-16.928 34.18-42.918 34.18z m188.165 0c-16.984 0-33.972-16.79-33.972-34.179 0-16.79 16.927-34.18 33.972-34.18 25.93 0 42.913 16.85 42.913 34.18 0 17.39-16.983 34.18-42.913 34.18z"
                  fill="#09BB07"
                  p-id="3845"></path>
              </svg>
            </span>
          </div>
          <div>
            <span class="register" @click="toRegister()">立即注册</span>
            <span @click="router.push('/forgetPassword')">忘记密码</span>
          </div>
        </div>

        <!-- 拼图验证码 -->
        <verify ref="verifyDom" class="verify-con" verify-type="LOGIN" @on-change="verifyChange"></verify>
      </div>
    </div>
    <!--底部模块-->
    <div class="login-footer">
      <div flex justify-center class="help">
        <div class="hover-color hover-pointer" @click="toArticle()">
          帮助
          <span class="line"></span>
        </div>
        <div class="hover-color hover-pointer" @click="toArticle('1371779927900160000')">
          隐私
          <span class="line"></span>
        </div>
        <div class="hover-color hover-pointer" @click="toArticle('1371992704333905920')">条款</div>
      </div>
      <div>
        Copyright © {{ data.myData.year }} - Present
        <a href="" target="_blank">{{ data.myData.copyright.title }}</a>
        版权所有
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import config from '@/config/index'
import { REQUIRED, VARCHAR20 } from '@/utils/validator'
import { login, smsLogin, getMemberMsg, webLogin, loginCallback } from '@/api/login'
import { sendSms } from '@/api/common'
import verify from '@/components/verify/index.vue'
import { md5 } from '@/utils/md5'
import { Message } from '@arco-design/web-vue'
import storage from '@/utils/storage'
// import { useUserStore } from '@/stores';
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'

const router = useRouter()
const route = useRoute()
// 状态管理
const store = useUserStore()
const { logoImg } = storeToRefs(store)
const loading = ref(false)
const verifyDom = ref()
interface formInterface {
  myData: {
    year: any
    copyright: any
  }
  loginType: string
  scannerCodeLoginFLag: boolean
  accountLoginForm: {
    username: string
    password: string
  }
  codeMsg: any
  verifyStatus: boolean
  interval: any
  time: number
  authCodeLoginForm: {
    mobile: string
    code: string
  }
}
// 数据集
const data = ref<formInterface>({
  myData: {
    year: new Date().getFullYear(),
    copyright: config
  },
  // 登录类型 账号登录:accountLogin，验证码登录:authCodeLogin，二维码登录qrCodeLogin
  loginType: 'accountLogin',
  // 是否为扫码登录
  scannerCodeLoginFLag: false,
  // 账号登录表单
  accountLoginForm: {
    username: '',
    password: ''
  },
  // 验证码文字
  codeMsg: '发送验证码',
  //  是否图片验证通过
  verifyStatus: false,
  interval: null, // 定时器
  time: 60, // 倒计时
  // 二维码登录表单
  authCodeLoginForm: {
    mobile: '',
    code: ''
  }
})
// 账号登录表单
const accountLoginRef = ref()
// 验证码登录
const authCodeLoginRef = ref()

// 切换登录类型
const toggleLoginType = (type: any) => {
  data.value.loginType = type
  data.value.scannerCodeLoginFLag = false
}
// 账号密码登录
const handleSubmit = async (type: any) => {
  const auth = await accountLoginRef.value?.validate()
  if (!auth && verifyDom.value) {
    // verifyDom.value.init()
    if (data.value.loginType === 'accountLogin') {
      // 账号密码登录
      const res = await login({
        username: data.value.accountLoginForm.username,
        password: data.value.accountLoginForm.password
      })
      if (res.data && res.data.success) {
        Message.loading('验证成功!正在登录中...')
        await loginSuccess(res)
      }
    } else {
      // 验证码登录
      data.value.verifyStatus = true
      verifyDom.value.verifyShow = false
    }
  }
}
// 发送手机验证码
const sendCode = async () => {
  if (data.value.time === 60) {
    if (data.value.authCodeLoginForm.mobile === '') {
      Message.warning('请先填写手机号')
      return
    }
    if (!data.value.verifyStatus) {
      Message.warning('请先完成安全验证')
      return
    }
    let params = {
      mobile: data.value.authCodeLoginForm.mobile,
      verificationEnums: 'LOGIN'
    }
    sendSms(params).then((res) => {
      if (res.data.success) {
        Message.success('验证码发送成功')
        data.value.interval = setInterval(() => {
          data.value.time--
          if (data.value.time === 0) {
            data.value.time = 60
            data.value.codeMsg = '重新发送'
            data.value.verifyStatus = false
            clearInterval(data.value.interval)
          } else {
            data.value.codeMsg = data.value.time
          }
        }, 1000)
      } else {
        Message.warning(res.data.message)
      }
    })
  }
}
// 开启滑块验证
const verifyBtnClick = async () => {
  if (!data.value.verifyStatus) {
    if (data.value.authCodeLoginForm.mobile === '') {
      Message.warning('请先填写手机号')
      return
    }
    verifyDom.value.init()
  }
}
// 验证码登录
const handleSubmitAuthCode = async () => {
  const auth = await authCodeLoginRef.value?.validate()
  if (!auth) {
    const res = await smsLogin(data.value.authCodeLoginForm)
    if (res.data && res.data.success) {
      Message.loading('验证成功!正在登录中...')
      await loginSuccess(res)
    }
  }
}
// 验证成功之后执行登录方法
async function loginSuccess(res: any) {
  console.log('登录成功', res)
  loading.value = true
  const { token } = res.data.result
  storage.setAccessToken(token)
  storage.setRefreshToken(token)
  storage.setGetTimes(0)
  // 获取用户信息
  await getMemberMsg().then((res) => {
    storage.setUserInfo(res.data.result)
    if (route.query.rePath) {
      let myPath = route.query.rePath as any
      if (route.query.query) {
        router.push({ path: myPath, query: JSON.parse(route.query.query) })
      } else {
        router.push({ path: myPath })
      }
    } else {
      router.push({ path: '/', query: {} })
    }
  })
}
// 验证是否正确
async function verifyChange(callback: any) {
  if (!callback.status) return
  try {
    if (data.value.loginType === 'accountLogin') {
      // 账号密码登录
      const res = await login({
        username: data.value.accountLoginForm.username,
        password: md5(data.value.accountLoginForm.password)
      })
      if (res.data && res.data.success) {
        Message.loading('验证成功!正在登录中...')
        await loginSuccess(res)
      }
    } else {
      // 验证码登录
      data.value.verifyStatus = true
      verifyDom.value.verifyShow = false
    }
  } catch (error) {
    loading.value = false
  }
  verifyDom.value.verifyShow = false
}
// 第三方登录
const handleWebLogin = (type: any) => {
  webLogin(type)
}
// 立即注册
async function toRegister() {
  await router.push({
    name: '/signUp',
    query: {}
  })
}
// 跳转文章详情
const toArticle = (id?: any) => {
  let routeUrl = router.resolve({ path: '/article', query: { id } })
  window.open(routeUrl.href, '_blank')
}

onMounted(() => {
  let uuid = route.query.state
  if (uuid) {
    storage.setUuid(uuid)
    loginCallback(uuid).then((res) => {
      if (res.data.success) {
        loginSuccess(res)
      }
    })
  }
})
</script>

<style scoped lang="less">
.login-container {
  height: 550px;
  background-image: url('https://lili-system.oss-cn-beijing.aliyuncs.com/background.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  .form-box {
    width: 350px;
    box-sizing: border-box;
    position: absolute;
    top: 80px;
    right: 15%;
    padding: 20px;
    background: rgba(250, 250, 250, 0.8);
    /*background-color: #d1d1d1;*/
    .login-title {
      display: flex;
      align-items: flex-end;
      justify-content: flex-start;
      margin-bottom: 20px;
      position: relative;
      > span {
        display: inline-block;
        margin: 0 6px;
        cursor: pointer;
      }
      .current {
        font-size: 16px;
        color: @theme_color;
        font-weight: bold;
      }
      .line {
        width: 1px;
        height: 14px;
        background-color: #dddddd;
      }
      .scanner-code {
        position: absolute;
        top: 6px;
        right: 0;
        color: @theme_color;
        font-size: 12px;
      }
    }
    .verify-con {
      position: absolute;
      right: 14px;
      top: 14px;
      z-index: 10;
    }
  }
  .other {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 18px 0 10px;
    font-size: 12px;
    > div {
      color: #666666;
      cursor: pointer;
      span {
        padding: 0 3px;
      }
      .register {
        color: @theme_color;
        margin-right: 10px;
      }
    }
  }
}
.demo-carousel {
  height: 550px;
  width: inherit;
  display: flex;
  justify-content: center;
}
.login-footer {
  width: 100%;
  text-align: center;
  margin: 0 auto;
  color: #aaaaaa;
  position: fixed;
  bottom: 4vh;
  font-size: 14px;
  letter-spacing: 1px;
  .help {
    > div {
      width: 80px;
      height: 20px;
      line-height: 16px;
      margin-bottom: 10px;
      text-align: center;
      position: relative;
      .line {
        position: absolute;
        top: 2px;
        right: 0px;
        display: block;
        width: 1px;
        height: 12px;
        background-color: #aaaaaa;
      }
    }
  }
  a {
    color: @primary_color;
  }
}
.code-msg {
  cursor: pointer;
}
</style>
